package com.base.cn.platform.os.common.mybatis.sharding;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.alibaba.druid.sql.ast.statement.SQLExprTableSource;
import com.alibaba.druid.sql.ast.statement.SQLInsertStatement;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlInsertStatement;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 插入SQL
 *
 * @author s.li
 * @create 2019-05-23 11:10
 */
public class InsertSql {

    /**
     * 处理添加SQL语句
     * @param insertStatement
     * @param tableNameList
     * @param columnSet
     * @param shardingValues
     */
    public static void insert(MySqlInsertStatement insertStatement, List<SQLExprTableSource> tableNameList, Set<String> columnSet, Map<String,Object> shardingValues){
        SQLExprTableSource tableSource = insertStatement.getTableSource();
        if(tableNameList !=null){
            tableNameList.add(tableSource);
        }
        if(columnSet !=null && shardingValues !=null){
            List<SQLInsertStatement.ValuesClause> valueList = insertStatement.getValuesList();
            List<SQLExpr> columnList = insertStatement.getColumns();
            for (int i = 0; i < columnList.size(); i++) {
                String name = ((SQLIdentifierExpr) columnList.get(i)).getName().replaceAll("`","");
                if(columnSet.contains(name.toLowerCase())){
                    List<SQLExpr>  list = valueList.get(0).getValues();
                    shardingValues.put(name,list.get(i).toString());
                }
            }
        }
    }
}
